package com.mycat.manager.controller.common;

import com.mycat.dao.entity.auth.Admin;
import com.mycat.manager.content.shiro.AccountStateException;
import com.mycat.manager.content.shiro.CustomerUserRealm;
import com.mycat.service.auth.AdminService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.Date;

/**
 * 登录
 *
 * @author Roger
 */
@Controller
@RequestMapping
public class LoginController {

    private static Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private AdminService adminService;

    /**
     * 页面跳转之登录页面
     */
    @RequestMapping("/toLogin")
    public String toLogin() {
        return "common/login";
    }

    /**
     * 登录
     *
     * @param userName 用户名
     * @param password 密码
     * @param model    Model
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(String userName, String password,String rememberMe, Model model) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
        token.setUsername(userName);
        token.setPassword(password.toCharArray());
        if(!StringUtils.isEmpty(rememberMe) && "YES".equals(rememberMe)){
            token.setRememberMe(true);
        }
        try {
            subject.logout();
            subject.login(token);
            // 显示调用授权
            subject.isPermitted("resource:authElement");
            // 修改用户登陆次数及当前登陆时间
            Admin admin = (Admin) subject.getSession().getAttribute(CustomerUserRealm.SESSION_LOGIN_USER);
            if(null != admin){
                admin.setLastActivity(new Date());
                admin.setLoginCount(admin.getLoginCount() + 1);
                adminService.updateAdmin(admin);
            }
            return "redirect:/index";
        } catch (UnknownAccountException e) {
            logger.error(e.getMessage(), e);
            model.addAttribute("userName", userName);
            model.addAttribute("errorMsg", e.getMessage());
            return "common/login";
        } catch (LockedAccountException e) {
            logger.error(e.getMessage(), e);
            model.addAttribute("userName", userName);
            model.addAttribute("errorMsg", e.getMessage());
            return "common/login";
        } catch (AccountStateException e) {
            logger.error(e.getMessage(), e);
            model.addAttribute("userName", userName);
            model.addAttribute("errorMsg", e.getMessage());
            return "common/login";
        } catch (IncorrectCredentialsException e) {
            logger.error(e.getMessage(), e);
            model.addAttribute("userName", userName);
            model.addAttribute("errorMsg", "用户密码错误！");
            return "common/login";
        } catch (ExcessiveAttemptsException e) {
            logger.error(e.getMessage(), e);
            model.addAttribute("userName", userName);
            model.addAttribute("errorMsg", e.getMessage());
            return "common/login";
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            model.addAttribute("userName", userName);
            model.addAttribute("errorMsg", "服务器异常,请稍后再试！");
            return "common/login";
        }
    }

    /**
     * 注销登录
     */
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:/toLogin";
    }
}
